package ar.edu.unq.tpi.uis.tepe3.wicket.model;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import ar.edu.unq.tpi.uis.tepe3.dominio.Folder;
import ar.edu.unq.tpi.uis.tepe3.dominio.User;
import ar.edu.unq.tpi.uis.tepe3.persistencia.HibernateUtil;
import ar.edu.unq.tpi.uis.tepe3.persistencia.UserDAO;

public class UserList {
	
	private Long id;
	private String name;
	private String pass;
	private List<User> result;
	
	public UserList(){
		super();
		this.loadAllUsers();
	}
	
	public void search() {
		this.result = this.getUserDAO().findByExample(this.getExample());
		this.getUserDAO().flush();
	}

	protected User getExample() {
//		return new User(this.getName(), this.getPass());
		return new User(this.getName());
	}

	public void clean() {
		this.result.clear();
	}

	public void add(User user) {
		//Videoclub.getHome(Socio.class).agregar(socio);
		//this.search();
	}
	
	public void loadAllUsers(){
//		Session sess = HibernateUtil.getSessionFactory().openSession();
//		sess.beginTransaction();
//		this.result = sess.createCriteria("ar.edu.unq.tpi.uis.tepe3.dominio.User").list();
//		sess.getTransaction().commit();
//		this.result = this.getUserDAO().findAll();
//		this.getUserDAO().flush();
		Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();
			this.result  = sess.createCriteria(User.class).list();
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally{
			if (sess.isOpen()) sess.close();
		}
	}

	public void delete(User user) {
		Session sess = HibernateUtil.getSessionFactory().openSession();
		sess.beginTransaction();
		sess.refresh(user);
		sess.delete(user);
		sess.getTransaction().commit();
		this.result.remove(user);
//		this.getUserDAO().makeTransient(user);
//		this.getUserDAO().flush();
	}

	public UserDAO getUserDAO() {
		return new UserDAO();
	}
	
	//********************
	// GETTERS Y SETTERS
	//********************

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public List<User> getResult() {
		return this.result;
	}

	public void setResult(List<User> users) {
		this.result = users;
	}

	

	
	
}
